import { NextResponse } from 'next/server';
import { cookies } from 'next/headers';
import { verifyToken } from '@/app/lib/auth';
import prisma from '@/app/lib/prisma';

export async function POST(request: Request) {
  try {
    const cookieStore = await cookies();
    const token = cookieStore.get('auth-token')?.value;

    if (!token) {
      return NextResponse.json({ message: '未授权' }, { status: 401 });
    }

    const payload = verifyToken(token);
    if (!payload) {
      return NextResponse.json({ message: '未授权' }, { status: 401 });
    }

    const { formData, recommendation } = await request.json();

    // 更新用户信息
    await prisma.user.update({
      where: { id: payload.userId },
      data: {
        height: Number(formData.height),
        weight: Number(formData.weight),
        age: Number(formData.age),
        gender: formData.gender,
        healthGoal: formData.goal,
      },
    });

    // 保存饮食推荐记录
    await prisma.dietRecommendation.create({
      data: {
        userId: payload.userId,
        height: Number(formData.height),
        weight: Number(formData.weight),
        age: Number(formData.age),
        gender: formData.gender,
        activityLevel: formData.activityLevel,
        goal: formData.goal,
        restrictions: formData.restrictions,
        dailyCalories: recommendation.dailyCalories,
        macronutrients: JSON.stringify(recommendation.macronutrients),
        mealPlan: JSON.stringify(recommendation.mealPlan),
        advice: recommendation.advice,
        tips: JSON.stringify(recommendation.tips),
      },
    });

    return NextResponse.json({ message: '保存成功' });
  } catch (error) {
    console.error('保存推荐错误:', error);
    return NextResponse.json(
      { message: '保存失败' },
      { status: 500 }
    );
  }
} 